package ex01.pyrmont;

import com.sky.JULLog.MyLogger;

import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.File;
import java.util.logging.Logger;


/**
 * 丐版  tomcat
 *  http://127.0.0.1:8080/index.html
 *  http://127.0.0.1:8080/SHUTDOWN
 */
public class TrashyTomcat {

    /**
     * WEB_ROOT is the directory where our HTML and other files reside.
     * For this package, WEB_ROOT is the "webroot" directory under the working  directory.
     * The working directory is the location in the file system from where the java command was invoked.
     * <p>
     * WEB_ROOT是HTML和其他文件所在的目录。
     * 对于这个包，WEB_ROOT是工作目录下的“webroot”目录。
     * 工作目录是在文件系统中调用java命令的位置。
     * <p>
     * 想想 tomcat 为什么要设计 webRoot ?
     */
    protected static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
    private static Logger log = MyLogger.getLogger(TrashyTomcat.class);

    static {

        log.info("存放静态文件的   web_root ==>  " + WEB_ROOT);
    }


    // shutdown command  浏览器 输入 路径匹配上 , 则 exit  丐版 tomcat
    static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    static final String SERVER_IP = "127.0.0.1";
    static final int PORT = 8080;
    // the shutdown command received
    private boolean shutdown = false;


    private void await() {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(PORT, 1, InetAddress.getByName(SERVER_IP));
            log.info("url==> http://" + SERVER_IP + ":"+ PORT);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        // Loop waiting for a request
        while (!shutdown) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();

                // create Request object and parse
                Request request = new Request(input);
                request.parse();

                // create Response object
                Response response = new Response(output);

                //从 request 中获取请求信息,  并返回数据给浏览器
                response.setRequest(request);
                response.sendStaticResource();

                // Close the socket
                socket.close();

                //check if the previous URI is a shutdown command
                shutdown = SHUTDOWN_COMMAND.equals(request.getUri());
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }


    }


    public static void main(String[] args) {
        TrashyTomcat server = new TrashyTomcat();
        server.await();
    }
}
